package analytics;

import java.io.IOException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

/**
 * Binds the {@link AnalyticsServer} to the Registry.
 * 
 * @author Lukas
 *
 */
public class Server {
	static int port;
	static String registryHost;
	
	/**
	 * Creates the registry (if it does not exist yet) and binds the {@link AnalyticsServer} to it.
	 * @param args
	 * @throws RemoteException 
	 */
	public static void main(String[] args) throws RemoteException {
		if (!loadProperties()) {
			return;
		}
		
		if (args.length != 1) {
			System.err.println("Usage: java analytics.Server <RMI-bindingName>");
			return;
		}
		//String objectName = "rmi://" + registryHost + ':' + port + '/' + args[0];
		
		Registry registry;
		try {
			registry = LocateRegistry.createRegistry(port);
		} catch (RemoteException e) {
			try {
				registry = LocateRegistry.getRegistry(registryHost, port);
			} catch (RemoteException e1) {
				System.err.println("could not get or create registry");
				return;
			}
		}
		
		AnalyticsServerImpl analyticsServer = new AnalyticsServerImpl();
		AnalyticsServer stub = (AnalyticsServer) UnicastRemoteObject.exportObject(analyticsServer, 0);
		registry.rebind(args[0], stub);
		
		/*try {
			System.in.read();
		} catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
		}*/
		System.out.println("Analytics Server running. Enter \"!exit\" to exit.");
		util.Util.waitForExit();
		
		System.out.println("Starting shutdown...");
		try {
			registry.unbind(args[0]);
		} catch (NotBoundException e) {
			System.err.println("ERROR:Could not unbind RMI-object");
		} catch (IOException e){
		    System.err.println("ERROR:"+e.getMessage());
		}
		UnicastRemoteObject.unexportObject(analyticsServer, true);
	}
	
	
	
	private static boolean loadProperties() {
		boolean ok = false;
		java.io.InputStream is = ClassLoader.getSystemResourceAsStream("registry.properties");
		if (is != null) {
			java.util.Properties props = new java.util.Properties();
			try {
				props.load(is);
				registryHost = props.getProperty("registry.host");
				port = Integer.parseInt(props.getProperty("registry.port"));
				ok = true;
			} catch (IOException e) {
				System.err.println("Could not load registry.properties");
			} catch (NumberFormatException e) {
				System.err.println("registry.port in registry.properties must be integer");
			}
			finally {
				try {
					is.close();
				} catch (IOException e) {
					System.err.println("could not close registry.properties");
				}
			}
		} else {
			System.err.println("Properties file not found!");
		}
		return ok;
	}
}
